import React, { useState, useEffect } from 'react';
import { 
  Card, Row, Col, Statistic, Progress, Table, Tabs, Typography, 
  Alert, Badge, Space, Tag, Button,   Spin, message, Empty
} from 'antd';
import {
  DashboardOutlined, CloudOutlined, ClockCircleOutlined, 
  WarningOutlined, CheckCircleOutlined,
  ArrowUpOutlined, ArrowDownOutlined, ReloadOutlined,
  HddOutlined, ApiOutlined, DatabaseOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { systemMonitorService } from '../services/systemMonitor';

import type { SystemResourceData, ServiceStatus, LogEntry, NetworkStats, StorageVolume, DatabaseStats } from '../services/systemMonitor';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

const SystemMonitor: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [systemResources, setSystemResources] = useState<SystemResourceData>({
    cpu: 0,
    memory: 0,
    disk: 0,
    status: 'normal',
    uptime: '',
    lastUpdated: ''
  });
  
  const [services, setServices] = useState<ServiceStatus[]>([]);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  
  const [networkStats, setNetworkStats] = useState<NetworkStats>({
    inbound: 0,
    outbound: 0,
    activeConnections: 0,
    totalTransferred: 0,
    requestsPerMinute: 0
  });

  const [storageVolumes, setStorageVolumes] = useState<StorageVolume[]>([]);
  const [databaseStats, setDatabaseStats] = useState<DatabaseStats>({
    connections: 0,
    activeQueries: 0,
    cacheHitRate: 0,
    avgQueryTime: 0
  });
  
  // 加载所有系统监控数据
  const loadAllData = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await systemMonitorService.getAllData();
      setSystemResources(data.systemResources);
      setServices(data.services);
      setLogs(data.logs);
      setNetworkStats(data.networkStats);
      setStorageVolumes(data.storageVolumes);
      setDatabaseStats(data.databaseStats);
    } catch (error) {
      console.error('加载系统监控数据失败:', error);
      message.error('加载系统监控数据失败，请稍后重试');
      setError('无法加载系统监控数据，请检查网络连接或服务器状态');
    } finally {
      setLoading(false);
    }
  };
  
  // 初始加载数据
  useEffect(() => {
    loadAllData();
    
    // 设置定时刷新 (每60秒刷新一次)
    const refreshInterval = setInterval(() => {
      loadAllData();
    }, 60000);
    
    // 组件卸载时清除定时器
    return () => clearInterval(refreshInterval);
  }, []);
  
  // 刷新数据
  const refreshData = () => {
    loadAllData();
  };
  
  // 重启服务
  const handleRestartService = async (serviceName: string) => {
    try {
      setLoading(true);
      await systemMonitorService.restartService(serviceName);
      message.success(`服务 ${serviceName} 已成功重启`);
      // 重新加载服务列表
      const updatedServices = await systemMonitorService.getServiceStatuses();
      setServices(updatedServices);
    } catch (error) {
      console.error(`重启服务 ${serviceName} 失败:`, error);
      message.error(`重启服务 ${serviceName} 失败，请稍后重试`);
    } finally {
      setLoading(false);
    }
  };
  
  // 查看服务日志
  const handleViewServiceLogs = async (serviceName: string) => {
    try {
      setLoading(true);
      // 获取指定服务的日志
      const allLogs = await systemMonitorService.getLogs();
      const filteredLogs = allLogs.filter(log => log.service === serviceName);
      setLogs(filteredLogs);
      // 切换到日志标签页
      document.getElementById('system-logs-tab')?.click();
    } catch (error) {
      console.error(`获取服务 ${serviceName} 的日志失败:`, error);
      message.error(`获取服务 ${serviceName} 的日志失败，请稍后重试`);
    } finally {
      setLoading(false);
    }
  };
  
  // 获取CPU使用率的状态颜色
  const getCpuStatusColor = (usage: number) => {
    if (usage >= 90) return '#ff4d4f';
    if (usage >= 70) return '#faad14';
    return '#52c41a';
  };
  
  // 获取内存使用率的状态颜色
  const getMemoryStatusColor = (usage: number) => {
    if (usage >= 85) return '#ff4d4f';
    if (usage >= 65) return '#faad14';
    return '#52c41a';
  };
  
  // 获取磁盘使用率的状态颜色
  const getDiskStatusColor = (usage: number) => {
    if (usage >= 90) return '#ff4d4f';
    if (usage >= 75) return '#faad14';
    return '#52c41a';
  };
  
  // 获取服务状态标签
  const getServiceStatusBadge = (status: string) => {
    switch (status) {
      case 'running':
        return <Badge status="success" text="运行中" />;
      case 'stopped':
        return <Badge status="error" text="已停止" />;
      case 'warning':
        return <Badge status="warning" text="警告" />;
      default:
        return <Badge status="default" text={status} />;
    }
  };
  
  // 获取日志级别标签
  const getLogLevelTag = (level: string) => {
    switch (level) {
      case 'info':
        return <Tag color="blue">信息</Tag>;
      case 'warning':
        return <Tag color="orange">警告</Tag>;
      case 'error':
        return <Tag color="red">错误</Tag>;
      default:
        return <Tag>{level}</Tag>;
    }
  };
  
  // 服务列表列定义
  const serviceColumns: ColumnsType<ServiceStatus> = [
    {
      title: '服务名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => getServiceStatusBadge(status),
    },
    {
      title: '运行时间',
      dataIndex: 'uptime',
      key: 'uptime',
    },
    {
      title: '内存使用',
      dataIndex: 'memory',
      key: 'memory',
      render: (memory) => `${memory} MB`,
    },
    {
      title: 'CPU使用',
      dataIndex: 'cpu',
      key: 'cpu',
      render: (cpu) => `${cpu}%`,
    },
    {
      title: '重启次数',
      dataIndex: 'restarts',
      key: 'restarts',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            size="small" 
            onClick={() => handleRestartService(record.name)}
          >
            重启
          </Button>
          <Button 
            type="text" 
            size="small" 
            onClick={() => handleViewServiceLogs(record.name)}
          >
            查看日志
          </Button>
        </Space>
      ),
    },
  ];
  
  // 系统日志列定义
  const logColumns: ColumnsType<LogEntry> = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: (level) => getLogLevelTag(level),
    },
    {
      title: '服务',
      dataIndex: 'service',
      key: 'service',
      width: 120,
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
    },
  ];

  // 如果有错误，显示错误信息
  if (error && !loading) {
    return (
      <div className="system-monitor-page">
        <div className="page-header" style={{ marginBottom: 24 }}>
          <Row gutter={[16, 16]} align="middle" justify="space-between">
            <Col>
              <Title level={2}>
                <CloudOutlined style={{ marginRight: 8 }} />
                系统监控
              </Title>
            </Col>
            <Col>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={refreshData}
                loading={loading}
              >
                刷新数据
              </Button>
            </Col>
          </Row>
        </div>
        
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
          action={
            <Button 
              size="small" 
              type="primary"
              onClick={refreshData}
            >
              重试
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div className="system-monitor-page">
      <div className="page-header" style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]} align="middle" justify="space-between">
          <Col>
            <Title level={2}>
              <CloudOutlined style={{ marginRight: 8 }} />
              系统监控
            </Title>
          </Col>
          <Col>
            <Space>
              <Text type="secondary">
                <ClockCircleOutlined style={{ marginRight: 4 }} />
                最后更新: {systemResources.lastUpdated}
              </Text>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={refreshData}
                loading={loading}
              >
                刷新数据
              </Button>
            </Space>
          </Col>
        </Row>
      </div>
      
      <Spin spinning={loading} tip="加载系统数据...">
        {/* 系统资源概览 */}
        <Card 
          title={
            <Space>
              <DashboardOutlined />
              <span>系统资源概览</span>
            </Space>
          } 
          bordered={false}
          style={{ marginBottom: 24 }}
        >
          <Row gutter={[24, 24]}>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="CPU使用率"
                  value={systemResources.cpu}
                  precision={1}
                  valueStyle={{ color: getCpuStatusColor(systemResources.cpu) }}
                  suffix="%"
                />
                <Progress 
                  percent={systemResources.cpu} 
                  status={systemResources.cpu > 90 ? "exception" : "normal"}
                  strokeColor={getCpuStatusColor(systemResources.cpu)}
                  showInfo={false}
                  style={{ marginTop: 8 }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="内存使用率"
                  value={systemResources.memory}
                  precision={1}
                  valueStyle={{ color: getMemoryStatusColor(systemResources.memory) }}
                  suffix="%"
                />
                <Progress 
                  percent={systemResources.memory} 
                  status={systemResources.memory > 85 ? "exception" : "normal"}
                  strokeColor={getMemoryStatusColor(systemResources.memory)}
                  showInfo={false}
                  style={{ marginTop: 8 }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="磁盘使用率"
                  value={systemResources.disk}
                  precision={1}
                  valueStyle={{ color: getDiskStatusColor(systemResources.disk) }}
                  suffix="%"
                />
                <Progress 
                  percent={systemResources.disk} 
                  status={systemResources.disk > 90 ? "exception" : "normal"}
                  strokeColor={getDiskStatusColor(systemResources.disk)}
                  showInfo={false}
                  style={{ marginTop: 8 }}
                />
              </Card>
            </Col>
          </Row>
          
          <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="系统运行时间"
                  value={systemResources.uptime}
                  valueStyle={{ fontSize: '16px' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="系统状态"
                  value={
                    systemResources.status === 'normal' ? '正常' :
                    systemResources.status === 'warning' ? '警告' : '错误'
                  }
                  valueStyle={{ 
                    color: 
                      systemResources.status === 'normal' ? '#52c41a' :
                      systemResources.status === 'warning' ? '#faad14' : '#ff4d4f',
                    fontSize: '16px'
                  }}
                  prefix={
                    systemResources.status === 'normal' ? <CheckCircleOutlined /> :
                    systemResources.status === 'warning' ? <WarningOutlined /> : <WarningOutlined />
                  }
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="活跃服务"
                  value={services.filter(s => s.status === 'running').length}
                  suffix={`/ ${services.length}`}
                  valueStyle={{ fontSize: '16px' }}
                />
              </Card>
            </Col>
          </Row>
        </Card>
        
        {/* 网络状态 */}
        <Card 
          title={
            <Space>
              <ApiOutlined />
              <span>网络状态</span>
            </Space>
          } 
          bordered={false}
          style={{ marginBottom: 24 }}
        >
          <Row gutter={[24, 24]}>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="入站流量"
                  value={networkStats.inbound}
                  precision={2}
                  valueStyle={{ color: '#1890ff' }}
                  prefix={<ArrowDownOutlined />}
                  suffix="MB/s"
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="出站流量"
                  value={networkStats.outbound}
                  precision={2}
                  valueStyle={{ color: '#52c41a' }}
                  prefix={<ArrowUpOutlined />}
                  suffix="MB/s"
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card bordered={false}>
                <Statistic
                  title="活跃连接数"
                  value={networkStats.activeConnections}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
          </Row>
          
          <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
            <Col xs={24} sm={12}>
              <Card bordered={false}>
                <Statistic
                  title="总传输数据"
                  value={networkStats.totalTransferred}
                  suffix="GB"
                />
              </Card>
            </Col>
            <Col xs={24} sm={12}>
              <Card bordered={false}>
                <Statistic
                  title="每分钟请求数"
                  value={networkStats.requestsPerMinute}
                  suffix="req/min"
                />
              </Card>
            </Col>
          </Row>
        </Card>
        
        {/* 服务状态和系统日志 */}
        <Tabs defaultActiveKey="1" style={{ marginBottom: 24 }}>
          <TabPane 
            tab={
              <span>
                <CloudOutlined />
                服务状态
              </span>
            } 
            key="1"
          >
            {services.length > 0 ? (
              <Table 
                columns={serviceColumns} 
                dataSource={services}
                rowKey="name"
                pagination={false}
                bordered
              />
            ) : (
              <Empty description="暂无服务数据" />
            )}
          </TabPane>
          
          <TabPane 
            tab={
              <span id="system-logs-tab">
                <FileTextOutlined />
                系统日志
              </span>
            } 
            key="2"
          >
            {logs.length > 0 ? (
              <Table 
                columns={logColumns} 
                dataSource={logs}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                bordered
              />
            ) : (
              <Empty description="暂无日志数据" />
            )}
          </TabPane>
          
          <TabPane 
            tab={
              <span>
                <HddOutlined />
                存储状态
              </span>
            } 
            key="3"
          >
            {storageVolumes.length > 0 ? (
              <>
                <Alert
                  message="存储系统状态"
                  description={`${storageVolumes.length}个存储卷正在运行`}
                  type="info"
                  showIcon
                  style={{ marginBottom: 16 }}
                />
                
                <Row gutter={[16, 16]}>
                  <Col span={24}>
                    <Card title="存储卷使用情况" bordered={false}>
                      <Row gutter={[16, 16]}>
                        {storageVolumes.map(volume => (
                          <Col xs={24} sm={8} key={volume.name}>
                            <Statistic 
                              title={volume.name} 
                              value={volume.usedPercentage} 
                              suffix="% 已使用" 
                              valueStyle={{ 
                                color: getDiskStatusColor(volume.usedPercentage) 
                              }}
                            />
                            <Progress 
                              percent={volume.usedPercentage} 
                              status={volume.usedPercentage > 90 ? "exception" : "normal"}
                              strokeColor={getDiskStatusColor(volume.usedPercentage)}
                            />
                            <div style={{ marginTop: 8 }}>
                              <Text type="secondary">
                                总容量: {volume.totalSpace} GB | 剩余: {volume.freeSpace} GB
                              </Text>
                            </div>
                          </Col>
                        ))}
                      </Row>
                    </Card>
                  </Col>
                </Row>
              </>
            ) : (
              <Empty description="暂无存储卷数据" />
            )}
          </TabPane>
          
          <TabPane 
            tab={
              <span>
                <DatabaseOutlined />
                数据库状态
              </span>
            } 
            key="4"
          >
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Card title="数据库概览" bordered={false}>
                  <Row gutter={[16, 16]}>
                    <Col xs={24} sm={6}>
                      <Statistic 
                        title="连接数" 
                        value={databaseStats.connections} 
                        valueStyle={{ color: '#1890ff' }}
                      />
                    </Col>
                    <Col xs={24} sm={6}>
                      <Statistic 
                        title="活跃查询" 
                        value={databaseStats.activeQueries} 
                        valueStyle={{ color: '#52c41a' }}
                      />
                    </Col>
                    <Col xs={24} sm={6}>
                      <Statistic 
                        title="缓存命中率" 
                        value={databaseStats.cacheHitRate} 
                        suffix="%" 
                        precision={1}
                        valueStyle={{ color: '#52c41a' }}
                      />
                    </Col>
                    <Col xs={24} sm={6}>
                      <Statistic 
                        title="平均查询时间" 
                        value={databaseStats.avgQueryTime} 
                        suffix="ms" 
                        precision={1}
                        valueStyle={{ color: '#1890ff' }}
                      />
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>
          </TabPane>
        </Tabs>
        
        {/* 系统警告 */}
        {systemResources.status === 'warning' || systemResources.status === 'error' ? (
          <Alert
            message="系统提醒"
            description={`系统状态异常，当前状态: ${systemResources.status === 'warning' ? '警告' : '错误'}，请检查系统日志获取详细信息。`}
            type={systemResources.status === 'error' ? "error" : "warning"}
            showIcon
            action={
              <Button 
                size="small" 
                type="primary"
                onClick={() => document.getElementById('system-logs-tab')?.click()}
              >
                查看详情
              </Button>
            }
          />
        ) : null}
      </Spin>
    </div>
  );
};

export default SystemMonitor; 